package org.hxzon.cyclone.pfgen;

import org.hxzon.cyclone.Particle;
import org.hxzon.cyclone.Vector3;

//弹簧的一点固定
public class ParticleAnchoredSpring implements ParticleForceGenerator {
    //弹簧的固定点
    protected Vector3 anchor;

    //弹簧系数
    protected double springConstant;

    //弹簧自然长度
    protected double restLength;

    //=============
    public ParticleAnchoredSpring() {
    }

    public ParticleAnchoredSpring(Vector3 anchor, double springConstant, double restLength) {
        init(anchor, springConstant, restLength);
    }

    public Vector3 getAnchor() {
        return anchor;
    }

    public void init(Vector3 anchor, double springConstant, double restLength) {
        this.anchor = anchor;
        this.springConstant = springConstant;
        this.restLength = restLength;
    }

    //============
    public void updateForce(Particle particle, double duration) {
        // 位移向量
        Vector3 force = particle.getPosition().copy();
        force.minusUpdate(anchor);

        // 弹簧当前长度
        double magnitude = force.magnitude();

        // 胡克定律
        magnitude = (restLength - magnitude) * springConstant;
        force.normalise();
        force.multiUpdate(magnitude);
        particle.addForce(force);
    }

}
